<template>
  <div class="work">
    <el-container>
      <el-header class="header">加班申请</el-header>
      <el-main>
        <!-- 操作按钮 -->
        <div class="btn">
          <el-button type="warning" @click="showDialog">发起新的</el-button>
          <el-upload
            action="/api/work/import"
            :headers="headers"
            name="excel"
            :data="{ userid: formData.userid }"
            :on-change="onChange"
            :on-success="onSuccess"
            :on-error="onError"
            :show-file-list="false"
            :disabled="uploading"
            accept=".xlsx;.xls"
          >
            <el-button :loading="uploading">导入</el-button>
          </el-upload>
          <el-button>
            <el-link :href="'/api/work/download?userid=' + formData.userid" target="_blank">导出</el-link>
          </el-button>
          <el-tabs v-model="activeName" class="tabs" @tab-change="handleClick">
            <el-tab-pane label="待办事项" name="1"></el-tab-pane>
            <el-tab-pane label="已办事项" name="2"></el-tab-pane>
            <el-tab-pane label="抄送事项" name="3"></el-tab-pane>
            <el-tab-pane label="我发起的" name="4"></el-tab-pane>
            <el-tab-pane label="全部数据" name="5"></el-tab-pane>
            <el-tab-pane label="概览" name="6"></el-tab-pane>
            <el-tab-pane label="统计报表" name="7"></el-tab-pane>
          </el-tabs>
        </div>
        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="_id" label="编号" show-overflow-tooltip />
          <el-table-column
            prop="status"
            label="当前流程"
            :formatter="formatterStatus"
          />
          <el-table-column prop="name" label="申请人" />
          <el-table-column prop="type" label="加班类型" />
          <el-table-column prop="reason" label="事由说明" width="150"/>
          <el-table-column prop="starttime" label="开始时间" :formatter="formatterTime" width="120"/>
          <el-table-column prop="endtime" label="结束时间" :formatter="formatterTime" width="120"/>
          <el-table-column prop="hours" label="加班时长" />
          <el-table-column prop="time" label="申请时间" :formatter="formatterTime" width="120"/>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="editRow(scope)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="deleteRow(scope)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
        <!-- 抽屉 -->
        <el-drawer
          ref="drawerRef"
          v-model="addDialog"
          title="加班申请"
          direction="rtl"
          custom-class="demo-drawer"
        >
          <div class="demo-drawer__content">
            <!-- 新增表单 -->
            <el-form
              :model="formData"
              label-position="top"
              :rules="rules"
              ref="formRef"
            >
            <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="申请人" prop="name">
                    <el-input v-model="formData.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所在部门">
                    <el-input v-model="formData.dept" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="加班类型" prop="type">
                    <el-select
                      v-model="formData.type"
                      placeholder="请选择加班类型"
                    >
                      <el-option
                        v-for="item in [
                          { label: '0', value: 1 },
                          { label: '1', value: 2 },
                        ]"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="加班事由说明" prop="reason">
                    <el-input
                      type="textarea"
                      v-model="formData.reason"
                      placeholder="输入内容"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="starttime">
                    <el-date-picker
                      v-model="formData.starttime"
                      type="date"
                      placeholder="选择一个开始时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endtime">
                    <el-date-picker
                      v-model="formData.endtime"
                      type="date"
                      placeholder="选择一个结束时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="加班时长" prop="hours">
                    <el-input v-model="formData.hours" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="demo-drawer__footer">
              <el-button @click="addDialog = false">取消</el-button>
              <el-button type="primary" @click="onSubmit(formRef)"
                >提交申请</el-button
              >
            </div>
          </div>
        </el-drawer>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { onMounted, ref,reactive } from "vue";
import { work_list,work_add,work_delete } from "../../api/index";
// 按钮
let headers=ref({Authorization:'Bearer'+' '+localStorage.getItem('token')})
let activeName = ref("");
let uploading = ref(false);
let handleClick = (name) => {
  console.log(activeName.value, name);
};
// 发起新的加班申请
let showDialog = () => {
  addDialog.value = true;
  formRef.value.resetFields();
  formData = ref({
    userid: JSON.parse(localStorage.getItem("userinfo"))._id,
    name: JSON.parse(localStorage.getItem("userinfo")).name,
    reason: "",
    starttime: "",
    endtime: "",
    hours: "",
  });
  delete fromData.value._id;
};
// 添加文件、上传成功和上传失败时的回调
let onChange = (upLoadFile, upLoadFiles) => {
  if (upLoadFile.percentage < 100) {
    uploading.value = true;
  }
};
// 文件上传成功时的回调
let onSuccess = (response, upLoadFile, upLoadFiles) => {
  uploading.value = false;
  if (response.code == 200) {
    ElNotification({
      title: "导入通知",
      message: response.msg,
      type: "success",
    });
  }
};
// 文件上传失败时的回调
let onError = (error, uploadFile, uploadFiles) => {
  uploading.value = false;
  if (error) {
    ElNotification({
      title: "导入通知",
      message: "导入失败!",
      type: "error",
    });
  }
};
// 表格
let tableData = ref([]);
let total = ref(0);
onMounted(async () => {
  let userinfo = JSON.parse(localStorage.getItem("userinfo"));
  // 请求加班申请列表
  let res = await work_list({ userid: userinfo._id, page: 1 });
  console.log(res);
  console.log(res.data.list);
  tableData.value = res.data.list;
  total.value = res.data.total;
});
// 格式化流程状态
let formatterStatus = function (row, column, cellValue, index) {
  return cellValue == 0 ? "审核中" : "已通过";
};
// 补零
let addZero = (num) => {
  return num < 10 ? "0" + num : num;
};
// 格式化时间
let formatterTime = function (row, column, cellValue, index) {
  let d = new Date(cellValue);
  return `${d.getFullYear()}-${addZero(d.getMonth() + 1)}-${addZero(
    d.getDate()
  )}`;
};
// 编辑
let editRow = (scope) => {
  // 弹出抽屉
  addDialog.value = true;
  // 显示当前行的出差申请数据(深拷贝)
  // scope.row 当前行的数据对象
  formData.value = JSON.parse(JSON.stringify(scope.row));
};
// 删除
let deleteRow = async (scope) => {
  let userinfo = JSON.parse(localStorage.getItem("userinfo"));
  let res = await work_delete({
    userid: userinfo._id,
    id: scope.row._id,
    page: 1,
  });
  if (res.data.code == 200) {
    ElNotification({
      title: "删除通知",
      message: res.data.msg,
      type: "success",
    });
    tableData.value = res.data.list;
    total.value = res.data.total;
  }
};
// 分页
let handleCurrentChange = async (page) => {
  let userinfo = JSON.parse(localStorage.getItem("userinfo"));
  // 请求对应页码的数据
  let res = await work_list({ userid: userinfo._id, page: page });
  tableData.value = res.data.list;
};
// 新增表单
let addDialog = ref(false);
let formData = ref({
  userid: JSON.parse(localStorage.getItem("userinfo"))._id,
  name: JSON.parse(localStorage.getItem("userinfo")).name,
  reason: "",
  starttime: "",
  endtime: "",
  hours: "",
});
let formRef = ref();
//验证 申请人
const validateName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入申请人"));
  } else {
    callback();
  }
};
//验证 出差事由
const validateReason = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入出差事由"));
  } else {
    callback();
  }
};
//验证 出发日期
const validateStarttime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择一个开始时间"));
  } else {
    if (
      new Date(formData.value.starttime) - new Date(formData.value.endtime) >
      0
    ) {
      //返回日期必须大于出发日期
      formData.value.starttime = "";
      formData.value.hours = "";
      callback(new Error("开始时间必须早于结束时间!"));
    } else if (formData.value.starttime && formData.value.endtime) {
      //出发日期,返回日期都存在, 计算总天数
      formData.value.hours =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (24 * 60 * 60 * 1000);
    }
    callback();
  }
};
//验证 返回日期
const validateEndtime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择一个结束时间"));
  } else {
    if (
      new Date(formData.value.starttime) - new Date(formData.value.endtime) >
      0
    ) {
      //返回日期必须大于出发日期
      formData.value.endtime = "";
      formData.value.days = "";
      callback(new Error("开始时间必须大于结束时间!"));
    } else if (formData.value.starttime && formData.value.endtime) {
      //出发日期,返回日期都存在, 计算总天数
      formData.value.hours =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (24 * 60 * 60 * 1000);
    }
    callback();
  }
};
//验证 出差总天数
const validateHours = (rule, value, callback) => {
  if (value === "" || Number(value) == 0) {
    callback(new Error("请填写正确的总时长"));
  } else {
    callback();
  }
};
//表单的验证规则 rules
const rules = reactive({
  name: [{ validator: validateName, trigger: "blur", required: true }],
  reason: [{ validator: validateReason, trigger: "blur", required: true }],
  starttime: [
    { validator: validateStarttime, trigger: "blur", required: true },
  ],
  endtime: [{ validator: validateEndtime, trigger: "blur", required: true }],
  hours: [{ validator: validateHours, trigger: "blur", required: true }],
});

// 提交表单
let onSubmit = (formRef) => {
  formRef.validate(async (valid) => {
    if (valid) {
      // 判断提交表单的动作是'新增'还是'编辑'，判断依据：fromData中是否有_id属性
      if (formData.value._id) {
        // 发送编辑请求
        // await business_edit(fromData.value)
        ElNotification({
          //弹出通知
          title: "编辑通知",
          message: "编辑成功!",
          type: "success",
        });
        addDialog.value = false;
      } else {
        // 发送新增出差申请
        let res = await work_add(formData.value);
        if (res.data.code == 200) {
          ElNotification({
            title: "新增通知",
            message: res.data.msg,
            type: "success",
          });
          addDialog.value = false;
          tableData.value = res.data.list;
          total.value = res.data.total;
          // 重置表单
          formRef.resetFields();
        } else {
          ElNotification({
            title: "新增通知",
            message: res.data.msg,
            type: "error",
          });
        }
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style scoped lang="scss">
.work {
  .header {
    display: flex;
    align-items: center;
    font-weight: 700;
  }
  .btn {
    display: flex;
    .tabs {
      margin-left: 30px;
    }
  }
  .pagination {
    margin: 20px 0;
  }
}
</style>